<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { DeptModel } from '@/api/model/model'
import { addApi, updateApi, deleteApi, queryAllApi } from '@/api/dept'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'

// 表格数据
const tableData = ref<DeptModel[]>([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 编辑表单
const formRef = ref<FormInstance>()
const form = reactive({
  id: undefined as number | undefined,
  name: '',
})

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' },
  ],
})

const dialogTitle = ref('添加部门')
const dialogVisible = ref(false)

// 多选处理
const multipleSelection = ref<DeptModel[]>([])

// 获取部门数据
const fetchDepts = async () => {
  try {
    loading.value = true
    const result = await queryAllApi()
    if (result.code === 1) {
      tableData.value = result.data
      pagination.total = result.data.length
    } else {
      ElMessage.error(result.msg || '获取部门数据失败')
    }
  } catch (error) {
    ElMessage.error('获取部门数据失败')
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchDepts()
}

// 处理每页数量变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchDepts()
}

// 处理多选
const handleSelectionChange = (val: DeptModel[]) => {
  multipleSelection.value = val
}

// 打开添加对话框
const openAddDialog = () => {
  dialogTitle.value = '添加部门'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row: DeptModel) => {
  dialogTitle.value = '编辑部门'
  form.id = row.id
  form.name = row.name
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.name = ''
}

// 提交表单
const submitForm = async () => {
  try {
    if (!(await formRef.value?.validate())) return

    let result
    if (form.id) {
      result = await updateApi(form)
      if (result.code === 1) ElMessage.success('部门更新成功')
      else throw new Error(result.msg || '更新部门失败')
    } else {
      result = await addApi({ name: form.name })
      if (result.code === 1) ElMessage.success('部门添加成功')
      else throw new Error(result.msg || '添加部门失败')
    }

    dialogVisible.value = false
    fetchDepts()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除部门
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该部门吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const result = await deleteApi([id])
    if (result.code === 1) {
      ElMessage.success('删除成功')
      fetchDepts()
    } else {
      throw new Error(result.msg || '删除部门失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除操作取消')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的部门')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${multipleSelection.value.length} 个部门吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const ids = multipleSelection.value
      .map((item) => item.id)
      .filter((id): id is number => id !== undefined)

    const result = await deleteApi(ids)
    if (result.code === 1) {
      ElMessage.success('批量删除成功')
      fetchDepts()
    } else {
      throw new Error(result.msg || '批量删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量删除操作取消')
    }
  }
}

// 搜索部门
const searchDept = () => {
  pagination.currentPage = 1
  fetchDepts()
}

onMounted(() => {
  fetchDepts()
})
</script>

<template>
  <div class="dept-container">
    <div class="header">
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="部门名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入部门名称"
              clearable
              @keyup.enter="searchDept"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchDept">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="operation-buttons">
      <el-button type="success" @click="openAddDialog">
        <el-icon><Plus /></el-icon> 新增部门
      </el-button>
      <el-button
        type="danger"
        :disabled="multipleSelection.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column type="index" label="序号" min-width="30" align="center" />
      <el-table-column prop="name" label="部门名称" min-width="150" />
      <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
      <el-table-column prop="updateTime" label="最后修改" min-width="180" align="center" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="openEditDialog(row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.header {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) th {
  background-color: #f0f2f5;
  color: #333;
  font-weight: bold;
}
</style>
